package com.tywj.lib.net.retrofit.request

import com.tywj.lib.core.common.util.JsonUtil
import com.tywj.lib.net.retrofit.HttpUtil
import com.tywj.lib.net.retrofit.callback.BaseCallback
import io.reactivex.Observable
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONArray
import org.json.JSONObject
import org.json.JSONTokener
import retrofit2.Response

/**
 * <pre>
 *     author :June Yang
 *     time   : 2020/6/10
 *     desc   : PUT请求
 *     version: 1.0.0
 * </pre>
 * @param isJson 数据类型是否为json，默认是false
 */
class PutRequest(url: String, private val isJson: Boolean = false) : BaseRequest<PutRequest>(url) {

    private val jsonObj = JSONObject()

    override fun param(key: String, value: String): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Boolean): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Int): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Long): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Float): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Double): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: JSONObject): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: JSONArray): PutRequest {
        jsonObj.put(key, value)
        return this
    }

    fun param(key: String, value: Collection<*>): PutRequest {
        jsonObj.put(key, JSONArray(JSONTokener(JsonUtil.toJson(value))))
        return this
    }

    override fun getRequestMethod(callback: BaseCallback<*>?): Observable<Response<ResponseBody>> {
        return if (isJson) {
            HttpUtil.httpConfig.httpMethod.put(url, headers, RequestBody.create(MEDIA_TYPE_JSON, jsonObj.toString()))
        } else {
            val builder = MultipartBody.Builder()
            val keys = jsonObj.keys()
            for (key in keys) {
                builder.addFormDataPart(key, jsonObj.get(key).toString())
            }
            if (jsonObj.length() == 0) {
                // 如果没有一个表单项都没有，则增加一个空字符串表单项
                builder.addFormDataPart("", "")
            }
            HttpUtil.httpConfig.httpMethod.put(url, headers, builder.setType(MultipartBody.FORM).build())
        }
    }
}